import { defineStore } from 'pinia'

export const useAuthStore = defineStore('auth', {
  state: () => ({
    isAuthenticated: false,
    user: {
      phone: null,
      avatar: null,
      nickname: null
    },
    token: null
  }),
  actions: {
    // 登录成功后调用此方法，传入后端返回的 EmployeeLoginVO 数据
    loginSuccess(loginVO) {
      const { phone, avatar, nickname, token } = loginVO

      // 更新 Pinia 状态
      this.isAuthenticated = true
      this.user = { phone, avatar, nickname }
      this.token = token

      // 持久化到 localStorage
      localStorage.setItem('isAuthenticated', this.isAuthenticated)
      localStorage.setItem('user', JSON.stringify(this.user))
      localStorage.setItem('token', token)
    },

    // 页面加载时恢复登录状态（用于刷新页面保持登录）
    restoreAuthFromLocalStorage() {
      const isAuthenticated = localStorage.getItem('isAuthenticated') === 'true'
      const user = JSON.parse(localStorage.getItem('user'))
      const token = localStorage.getItem('token')

      if (isAuthenticated && user && token) {
        this.isAuthenticated = isAuthenticated
        this.user = user
        this.token = token
      }
    },

    // 退出登录时清除状态和本地存储
    logout() {
      this.isAuthenticated = false
      this.user = null
      this.token = null

      localStorage.removeItem('isAuthenticated')
      localStorage.removeItem('user')
      localStorage.removeItem('token')
    }
  }
})